<template>
  <div id="register">
  <h2>用户注册</h2>
  <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
  <form @submit.prevent="register">
    <div class="form-group">
      <label for="username">用户名:</label>
      <input type="text" id="username" v-model="username" required>
    </div>
    <div class="form-group">
      <label for="password">密码:</label>
      <input type="password" id="password" v-model="password" required>
    </div>
    <div class="form-group">
      <label for="confirmPassword">确认密码:</label>
      <input type="password" id="confirmPassword" v-model="confirmPassword" required>
    </div>
    <button type="submit">注册</button>
  </form>

</div>

</template>

<script>
import axios from "axios";

export default {
    name: "Register",
    data() {
    return {
      username: '',
      password: '',
      confirmPassword:'',
      errorMessage:''
    };
  },
  methods: {
    register() {
      // TODO:
      if (this.password !== this.confirmPassword) {
        // 密码与确认密码不匹配
        this.errorMessage = '密码与确认密码不匹配';
      }else {
          axios.post(`http://localhost:5000/user/register`, {
        username: this.username,
        password: this.password
      }, {
        "Content-Type": "application/json;charset=UTF-8",
      }).then(res => {
        if (res.data.status === "SUCCESS") {
          alert("注册成功！")
          this.$router.push('/')
        } else if (res.data.status === "FAILED") {
          // 登录失败
          this.errorMessage = '注册失败';
        } else {
          this.errorMessage = '未知错误';
        }
      }).catch(error => {
        console.log(error)
        })
      }

      }

    }

};

</script>

<style scoped>
#register{
    position: relative;
    margin-left: 500px;
    margin-right: -100px
}
#app {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

h2 {
  text-align: center;
}

.form-group {
  margin-bottom: 10px;
}

label {
  display: block;
}

input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

button {
  display: block;
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.error-message {
  color: red;
  text-align: center;
  margin-top: 10px;
}

</style>